package com.dahuyou.trigger.http;

import com.dahuyou.types.util.HttpURLClient;
import com.dahuyou.types.util.JwtUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 模拟SSO的第一个应用
 */
@Controller
@RequestMapping("/app1")
public class App1Controller {
    private static final String oauthURl = "http://localhost:8899/oidcProvider/exchangeAccessTokenByCode";
    private static final String queryUserInfoURl = "http://localhost:8899/oidcProvider/queryUserInfo";
    // username -> id token (分布式环境可考虑存储到redis等nosql中)
    private static final Map<String, String> idtokenMap = new HashMap<>();
    // username -> access token (分布式环境可考虑存储到redis等nosql中)
    private static final Map<String, String> accesstokenMap = new HashMap<>();

    @RequestMapping("/index")
    public String methodOne(HttpServletRequest request) {
        request.setAttribute("word", "小姐姐，我需要你的授权，才能看到你的个人信息！");
        return "app1_index";
    }

    /**
     * 接收授权服务器授权码的回调接口
     * @param request
     * @return
     */
    @RequestMapping("/receiveAuthCode")
//    @ResponseBody
//    public String eceiveAuthCode(HttpServletRequest request) {
    public void receiveAuthCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //授权码许可流程，DEMO CODE
        String code = request.getParameter("code");
        Map<String, String> params = new HashMap<String, String>();
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        params.put("app_id", "APPID_RABBIT");
        params.put("app_secret", "APPSECRET_RABBIT");
        System.out.println("通过code交换id token和access token");
        String accessTokenAndAccessToken  = HttpURLClient.doPost(oauthURl, HttpURLClient.mapToStr(params));
        System.out.println("成功拿到了accessTokenAndAccessToken: " + accessTokenAndAccessToken + ", 接着就可以拿来访问受保护资源了！");
       /* //使用 accessToken 请求受保护资源服务
        Map<String, String> paramsMap = new HashMap<String, String>();
        paramsMap.put("app_id", "APPID_RABBIT");
        paramsMap.put("app_secret", "APPSECRET_RABBIT");
        paramsMap.put("token", accessToken);
        String result = HttpURLClient.doPost(protectedURl, HttpURLClient.mapToStr(paramsMap));*/
//        return "成功拿到了access_token: " + accessTokenAndAccessToken + ", 接着就可以拿来访问受保护资源了！";
        // 记录id token和access_token
        String accessToken = accessTokenAndAccessToken.split("\\|")[0];
        String idToken = accessTokenAndAccessToken.split("\\|")[1];
        String subjectFromJwt = JwtUtils.getSubjectFromJwt(idToken);
        idtokenMap.put(subjectFromJwt, idToken);
        accesstokenMap.put(subjectFromJwt, accessToken);
        System.out.println("subjectFromJwt: " + subjectFromJwt);

        /** 调用授权接口 **/
        // 使用access_token查询用户信息，这就输入授权相关内容了
        Map<String, String> params111 = new HashMap<String, String>();
        params111.put("sub", subjectFromJwt);
        String userInfo  = HttpURLClient.doPost(queryUserInfoURl, HttpURLClient.mapToStr(params111));
        System.out.println("通过access_token成功获取用户信息: " + userInfo);
//        request.setAttribute("sub", subjectFromJwt);
//        request.setAttribute("userInfo", userInfo);
        response.sendRedirect("http://localhost:8899/app1/home?sub=" + URLEncoder.encode(subjectFromJwt, "UTF-8") + "&userInfo=" + URLEncoder.encode(userInfo, "UTF-8"));
//        return "app1_home";
    }

    /**
     * 跳转到首页
     * @param request
     * @return
     */
    @RequestMapping("/home")
    public String home(HttpServletRequest request) {
        request.setAttribute("sub", request.getParameter("sub"));
        request.setAttribute("userInfo", request.getParameter("userInfo"));
//        request.setAttribute("userInfo", "xxxxxxbbbbb");
        return "app1_home";
    }

}